package pers.zh.parking.mvp.presenter;

import android.app.Application;

import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import pers.zh.parking.common.BaseObserver;
import pers.zh.parking.common.BaseResponse;
import pers.zh.parking.common.RxScheduler;
import pers.zh.parking.data.UserSettings;
import pers.zh.parking.data.entity.User;
import pers.zh.parking.mvp.contract.LoginContract;
import pers.zjc.commonlibs.util.SPUtils;
import pers.zjc.commonlibs.util.StringUtils;

@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {

    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void login(String account, String password) {
        if (StringUtils.isEmpty(account)) {
            mRootView.showMessage("账号不能为空");
            return;
        }
        if (StringUtils.isEmpty(password)) {
            mRootView.showMessage("密码不能为空");
            return;
        }
        mModel.login(account, password)
              .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
              .compose(RxScheduler.Obs_io_main())
        .subscribe(new BaseObserver<BaseResponse<User.Wrap>>(mRootView) {
            @Override
            public void onSuccess(BaseResponse<User.Wrap> response) {
                User user = response.getData().getUser();
                UserSettings.getInstance().setUserId(String.valueOf(user.getUserId()));
                UserSettings.getInstance().setUserName(String.valueOf(user.getUserName()));
                UserSettings.getInstance().setPassword(String.valueOf(user.getPassword()));
                UserSettings.getInstance().setAccount(String.valueOf(user.getAccount()));
                UserSettings.getInstance().setDescription(String.valueOf(user.getDescription()));
                UserSettings.getInstance().setRole(String.valueOf(user.getRole()));
                UserSettings.getInstance().setAvatar(String.valueOf(user.getAvatar()));
                UserSettings.getInstance().setLogin(true);
                mRootView.showMessage(String.format("欢迎登录，%s", user.getUserName()));
                mRootView.loginSuccess();
            }
        });
    }
}
